package com.tyut.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;

@Controller
public class FileUploadController {

    @RequestMapping(value = "/fileUpload",method = RequestMethod.GET)
    public String toUpload(){
        return "fileUpload";
    }

    @RequestMapping(value = "/fileUpload",method = RequestMethod.POST)
    public String handleFormUpload(@RequestParam("name")String name, @RequestParam("uploadfile")List<MultipartFile> uploadfile, HttpServletRequest request){
        if(!uploadfile.isEmpty() && uploadfile.size()>0){
            for(MultipartFile file:uploadfile){
                String originalFilename = file.getOriginalFilename();
                String dirPath = request.getServletContext().getRealPath("/upload");
                File filePath = new File(dirPath);
                if(!filePath.exists()){
                    filePath.mkdirs();
                }
                String newFilename = "\\"+name+"_"+ UUID.randomUUID()+"_"+originalFilename;
                try{
                    file.transferTo(new File(dirPath + newFilename));
                }catch (Exception e){
                    e.printStackTrace();
                    return "error";
                }
            }
            return "success";
        }else {
            return "error";
        }
    }

}
